import 'dart:io';
import 'dart:typed_data';

// import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_scankit/flutter_scankit.dart';
import 'package:get/get.dart';
import 'package:r_upgrade/r_upgrade.dart';
import 'package:tencent_kit/tencent_kit.dart';
import 'package:x_common_utils/cache_encryption_decrypt_util/cache_encryption_decrypt_util.dart';
import 'package:xinxuan/common/dialogs/notice_dialog.dart';
import 'package:xinxuan/common/dialogs/sign_dialog.dart';
import 'package:xinxuan/common/dialogs/sign_success_dialog.dart';
import 'package:xinxuan/common/dialogs/upload_apk_dialog.dart';
import 'package:xinxuan/config/app_config.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/router/app_routers.dart';
import 'package:xinxuan/utils/cache_key_util.dart';
import 'package:xinxuan/utils/color_util.dart';
import 'package:xinxuan/vo/announcements_vo.dart';
import 'package:xinxuan/vo/sign_record_vo.dart';
import 'package:xinxuan/vo/sign_vo.dart';
import 'package:xinxuan/vo/user_data_vo.dart';
import 'package:xinxuan/vo/version_vo.dart';
import 'dart:ui' as ui;
import 'package:permission_handler/permission_handler.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

class CommonPageController extends GetxController {

  final FlutterScankit flutterScankit = FlutterScankit();
  
  /// 版本
  var appVersion = ''.obs;
  /// 设备 IOS、Android
  var appDeviceType = ''.obs;
  /// 是否为审核版本
  var isRevirew = false.obs;
  /// 是否展示签到
  var isSign = false.obs;
  /// tabIndex
  var tabIndex = 0.obs;
  /// 是否已登录
  var isAuthenticated = false.obs;
  /// 用户信息
  var userData = UserData(
    nickname: '', 
    avatar: '', 
    levelStr: '', 
    invitationCode: '', 
    invitationUrl: '',
    isTeamLeader: 0,
    teamId: 0,
    isLocation: 0,
    isInvatition: 0,
    isSignDaily: 0,
    isWriteoffOfficer: 0,
    integral: Integral(
      total: 0,
      consume: 0,
      expire: 0,
      used: 0,
      available: 0,
      expired: 0
    ),
    statistics: Statistics(
      seckill: [0, 0, 0, 0, 0],
      shopping: [0, 0, 0]
    )
  ).obs;
  /// 用户昵称
  String nickname = '';
  /// 微信号
  String wechat = '';
  // /// 认证信息
  // var authenticationData = AuthenticationData().obs;
  // /// 真实姓名
  // var realname = '';
  // /// 身份证号码
  // var number = ''.obs;
  /// 安装包下载信息
  DownloadInfo? downloadInfo;
  /// 定位信息
  // Location? _location;
  /// 是否已上传定位信息
  bool isUploadLocation = false;
  /// 最新版本信息
  var versionData = VersionData().obs;
  

  /// 签到记录
  var signRecordArr = <SignRecordItem>[].obs;

  /// 是否已自动展示签到弹窗
  var openSignFun = 0.obs;

  @override
  void onInit() {
    print('common_page_controller..........');
    downloadListen();
    EasyLoading.instance
      ..displayDuration = const Duration(milliseconds: 2000)
      ..indicatorType = EasyLoadingIndicatorType.fadingCircle
      ..toastPosition = EasyLoadingToastPosition.center
      ..loadingStyle = EasyLoadingStyle.custom
      ..radius = 5
      ..backgroundColor = bgBlackColor_50
      ..boxShadow = <BoxShadow>[]
      ..indicatorColor = bgWhiteColor
      ..textColor = textWhiteColor
      ..maskColor = bgBlackColor_50
      ..progressColor = bgBlackColor_50
      ..userInteractions = true
      ..successWidget = Image.asset(
        'assets/icons/icon_success.png',
        width: 28,
        height: 28
      )..dismissOnTap = false;
    
    flutterScankit.addResultListen((String res) {
      Uri u = Uri.parse(res);
      if (!u.queryParameters.containsKey('voucherCode')) {
        EasyLoading.showToast('参数异常');
        return;
      } 
      Get.toNamed(
        '${AppRouters.COMMON_PAGE}${AppRouters.WRITE_OFF_PAGE}',
        arguments: {
          'code': u.queryParameters['voucherCode']!
        }
      );
    });
    super.onInit();
  }
  
  /// 检查用户是否登录
  Future<bool> checkLogin({bool loading = true}) async {
    // String _token = await CacheEncryptionDecryptUtil.getStringCacheEncryption(key: CacheKeyUtil.token);
    isAuthenticated.value = !TextUtil.isEmpty(AppConfig.token);
    if (!isAuthenticated.value) {
      userData.value = UserData(
        nickname: '', 
        avatar: '', 
        levelStr: '', 
        invitationCode: '', 
        invitationUrl: '',
        isTeamLeader: 0,
        isLocation: 0,
        teamId: 0,
        isInvatition: 0,
        isSignDaily: 0,
        isWriteoffOfficer: 0,
        integral: Integral(
          total: 0,
          consume: 0,
          expire: 0,
          used: 0,
          available: 0,
          expired: 0
        ),
        statistics: Statistics(
          seckill: [0, 0, 0, 0, 0],
          shopping: [0, 0, 0]
        )
      );
      showNoticeDialog();
      update();
      return false;
    }
    getUserInfo(loading: loading);
    return isAuthenticated.value;
  }

  /// 获取用户信息
  getUserInfo({bool loading = true}) async {
    UserDataVo userDataVo = await HttpUtilService.getUserInfo(loading: loading);
    userData.value = userDataVo.data!;
    // userData.value.isSignDaily = 0;
    // userData.value.isInvatition = 0;
    openSignDialog();
    update();
    if (isUploadLocation) {
      return;
    }
    isUploadLocation = true;
    // await getLocation();
    // if (userData.value.isLocation == 1 && _location != null) {
    //   HttpUtilService.userLocations(
    //     address: '${_location!.address}', 
    //     latLng: '${_location!.latLng!.latitude},${_location!.latLng!.longitude}', 
    //     country: '${_location!.country}', 
    //     province: '${_location!.province}', 
    //     city: '${_location!.city}', 
    //     cityCode: '${_location!.cityCode}', 
    //     adCode: '${_location!.adCode}', 
    //     district: '${_location!.district}', 
    //     poiName: '${_location!.poiName}', 
    //     street: '${_location!.street}'
    //   );
    // }
  }

  /// 修改昵称
  editUserName() async {
    if (TextUtil.isEmpty(nickname)) {
      nickname = '${userData.value.nickname}';
    }
    Map<String, dynamic> param = {
      'nickname': nickname
    };
    UserDataVo userDataVo = await HttpUtilService.editUser(param: param);
    userData.value = userDataVo.data!;
    Get.back();
    getUserInfo();
  }
  
  /// 修改微信号
  editUserWechat() async {
    if (TextUtil.isEmpty(wechat)) {
      EasyLoading.showToast('请输入微信号');
      return;
    }
    Map<String, dynamic> param = {
      'wechat': wechat
    };
    UserDataVo userDataVo = await HttpUtilService.editUser(param: param);
    userData.value = userDataVo.data!;
    Get.back();
    getUserInfo();
  }

  /// 获取实名认证信息
  // getAuthenticationData() async {
  //   AuthenticationVo authenticationVo = await HttpUtilService.getAuthenticationData();
  //   authenticationData.value = authenticationVo.data!;
  //   if (!TextUtil.isEmpty(authenticationData.value.realname)) {
  //     realname = authenticationData.value.realname!;
  //   }
  //   if (!TextUtil.isEmpty(authenticationData.value.number)) {
  //     number = authenticationData.value.number!;
  //   }
  //   update();
  // }

  

  /// 检查版本信息
  checkAppVersion({bool showLoading = true}) async {
    VersionVo versionVo = await getVersionMsg();
    if (versionVo.data!.isUpdate == 1) {
      Get.dialog(
        UploadApkDialog(
          versionVo.data!.downloadUrl!, 
          versionVo.data!.content!,
          versionVo.data!.version!, 
          versionVo.data!.forcedUpdate!
        ),
        barrierDismissible: false,
      );
    } else {
      if (showLoading) {
        EasyLoading.showToast('已经是最新版本');
      }
    }
  }

  /// 获取最新版本信息
  Future<VersionVo> getVersionMsg() async {
    VersionVo versionVo = await HttpUtilService.checkVersion();
    versionData.value = versionVo.data!;
    // versionVo.data!.isReview = 1;
    // versionData.value.isUpdate = 1;
    isRevirew.value = versionVo.data!.isReview == 1;
    isSign.value = versionData.value.isSign == 1;
    return versionVo;
  }

  /// 同意授权
  consentAuthorization() async {
    // await getVersionMsg();
    // checkLogin();
    // CacheEncryptionDecryptUtil.saveBoolCacheEncryption(key: CacheKeyUtil.showUserAgreement, value: true);
    // if (isRevirew.value) {
    //   Get.offAllNamed(AppRouters.REVIEW_COMMON_PAGE);
    // } else {
    //   Get.offAllNamed(AppRouters.COMMON_PAGE);
    // }
    checkAppVersion(showLoading: false);
    checkLogin();
    CacheEncryptionDecryptUtil.saveBoolCacheEncryption(key: CacheKeyUtil.showUserAgreement, value: true);
    Get.offAllNamed(AppRouters.COMMON_PAGE);
  }
  
  /// 下载并安装Apk
  downloadApk(String apkUrl, String versionName, { bool showLoading = false}) async {
    if (showLoading) {
      EasyLoading.instance.userInteractions = false;
      EasyLoading.show();
    }
    if (downloadInfo == null) {
      EasyLoading.showToast('后台下载中', toastPosition: EasyLoadingToastPosition.bottom);
      await RUpgrade.upgrade(
        apkUrl,
        fileName: '星力优选',
        notificationStyle: NotificationStyle.planTimeAndSpeech
      );
    } else {
      if (downloadInfo!.status == DownloadStatus.STATUS_PAUSED) {
        RUpgrade.upgradeWithId(downloadInfo!.id!);
        EasyLoading.showToast('已继续下载', toastPosition: EasyLoadingToastPosition.bottom);
      }
      if (downloadInfo!.status == DownloadStatus.STATUS_PENDING) {
        RUpgrade.cancel(downloadInfo!.id!);
        downloadInfo = null;
        downloadApk(apkUrl, versionName);
      }
      if (downloadInfo!.status == DownloadStatus.STATUS_RUNNING) {
        EasyLoading.showToast('后台下载中', toastPosition: EasyLoadingToastPosition.bottom);
      }
      if (downloadInfo!.status == DownloadStatus.STATUS_SUCCESSFUL) {
        EasyLoading.showToast('下载成功', toastPosition: EasyLoadingToastPosition.bottom);
        downloadInfo = null;
      }
      if (downloadInfo!.status == DownloadStatus.STATUS_FAILED) {
        EasyLoading.showToast('下载失败，将重新下载', toastPosition: EasyLoadingToastPosition.bottom);
        RUpgrade.cancel(downloadInfo!.id!);
        downloadInfo = null;
        downloadApk(apkUrl, versionName);
      }
      if (downloadInfo!.status == DownloadStatus.STATUS_CANCEL) {
        EasyLoading.showToast('下载取消，将重新下载', toastPosition: EasyLoadingToastPosition.bottom);
        RUpgrade.cancel(downloadInfo!.id!);
        downloadInfo = null;
        downloadApk(apkUrl, versionName);
      }
    }
  }

  /// 监听下载进度
  downloadListen() {
    if (Platform.isAndroid) {
      RUpgrade.stream.listen((DownloadInfo info) async {
        downloadInfo = info;
      });
    }
  }

  /// 注销账号
  cancelAccount() async {
    bool res = await HttpUtilService.cancelAccount();
    if (res) {
      logOut();
    }
  }

  /// 退出登录
  logOut() async {
    AppConfig.token = '';
    await CacheEncryptionDecryptUtil.removeByKey(key: CacheKeyUtil.token);
    checkLogin();
    Get.offAllNamed(AppRouters.COMMON_PAGE);
  }

  /// 一键回收
  seckillRecovery () async {
    bool res = await HttpUtilService.seckillRecovery();
    if (res) {
      Get.back();
      EasyLoading.showToast('回收成功');
    }
  }

  /// 保存分享图
  saveImage(GlobalKey globalKey) async {
    RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    var image = await boundary.toImage(pixelRatio: 2.5);
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData!.buffer.asUint8List();
    PermissionStatus status = await Permission.storage.request();
    if (status.isGranted) {
      var result = await ImageGallerySaver.saveImage(pngBytes, quality: 100, name: "shareImage");
      if (result['isSuccess']) {
        EasyLoading.showToast('图片保存成功');
        Get.back();
      } else {
        EasyLoading.showToast('图片保存失败');
      }
    } else {
      EasyLoading.showToast('请授权权限');
    }
  }

  /// 分享到微信
  shareToWeChar() async {
    await fluwx.registerWxApi(appId: AppConfig.wxAppId, universalLink: AppConfig.universalLink);
    if (!await fluwx.isWeChatInstalled) {
      EasyLoading.showToast('请安装微信');
      return;
    }
    fluwx.shareToWeChat(fluwx.WeChatShareWebPageModel(
      AppConfig.shareWebPage,
      title: '星力优选',
      thumbnail: fluwx.WeChatImage.asset('assets/icons/icon_logo.png'),
      description: '诚邀您加入星力优选',
      scene: fluwx.WeChatScene.SESSION
    ));
  }

  shareToQQ() async {
    await Tencent.instance.registerApp(appId: AppConfig.qqAppId);
    if (!await Tencent.instance.isQQInstalled()) {
      EasyLoading.showToast('请安装QQ');
      return;
    }
    await Tencent.instance.shareWebpage(
      scene: TencentScene.SCENE_QQ, 
      title: '星力优选', 
      targetUrl: AppConfig.shareWebPage,
      appName: '星力优选',
      summary: '诚邀您加入星力优选'
    );
  }

  /// 获取定位
  // getLocation() async {
  //   if (await requestPermission()) {
  //     final location = await AmapLocation.instance.fetchLocation();
  //     _location = location;
  //   }
  // }

  /// 获取定位权限
  Future<bool> requestPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        EasyLoading.showToast('请开启定位权限');
        return false;
      }
    }
  }

  /// 打开微信客服
  openWeChatCustomerServiceChat() async {
    await fluwx.registerWxApi(
      appId: AppConfig.wxAppId,
      universalLink: AppConfig.universalLink
    );
    if (!await fluwx.isWeChatInstalled) {
      EasyLoading.showToast('请先安装微信');
      return;
    }
    fluwx.openWeChatCustomerServiceChat(
      url: AppConfig.wxCustomerServiceUrl, 
      corpId: AppConfig.corpId
    );
  }

  /// 打开APP时校验，未签到，并且已登录的状态，则打开签到弹窗
  openSignDialog() {
    if (isAuthenticated.value && userData.value.isSignDaily == 0 && openSignFun.value == 0 && isSign.value) {
      openSignFun.value = 1;
      userSignDialog();
    } else {
      showNoticeDialog();
    }
  }

  /// 签到弹窗
  userSignDialog() async {
    if (!isAuthenticated.value) {
      Get.toNamed('${AppRouters.COMMON_PAGE}${AppRouters.LOGIN_PAGE}');
      return;
    }
    await getUserSignRecord();
    Get.dialog(SignDialog()).then((res) {
      showNoticeDialog();
    });
  }

  /// 用户签到
  userSign() async {
    SignVo signVo = await HttpUtilService.userSign();
    if (signVo.data != null) {
      Get.back();
      Get.dialog(SignSuccessDialog(
        integral: '${signVo.data!.integral}',
      ));
      checkLogin();
    }
  }

  /// 获取用户签到记录
  getUserSignRecord() async {
    SignRecordVo signRecordVo = await HttpUtilService.getUserSignRecord();
    signRecordArr.value = signRecordVo.data!;
    update();
  }

  /// 首次打开应用时，展示公告
  showNoticeDialog() async {
    AnnouncementsVo? announcementsVo = await HttpUtilService.getAnnouncements(loading: false);
    if (announcementsVo != null) {
      // await CacheEncryptionDecryptUtil.removeByKey(key: CacheKeyUtil.noticeArr);
      List<String> _noticeArr = await CacheEncryptionDecryptUtil.getStringArrCacheEncryption(key: CacheKeyUtil.noticeArr, defaultValue: []);
      if (!_noticeArr.contains('${announcementsVo.data!.id}')) {
        _noticeArr.add('${announcementsVo.data!.id}');
        await CacheEncryptionDecryptUtil.saveStringArrCacheEncryption(key: CacheKeyUtil.noticeArr, value: _noticeArr);
        Get.dialog(
          NoticeDialog(
            title: '${announcementsVo.data!.title}',
            description: '${announcementsVo.data!.description}',
          ),
          barrierDismissible: false
        );
      }
    }
  }

  /// 检查摄像头权限
  Future<bool> checkCameraPermission() async {
    // //获取当前的权限
    var status = await Permission.camera.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.camera.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        EasyLoading.showToast('请开启摄像权限');
        return false;
      }
    }
  }

  /// 检查图库权限
  Future<bool> checkPhotosPermission() async {
    // //获取当前的权限
    var status = await Permission.photos.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.photos.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        EasyLoading.showToast('请开启图库权限');
        return false;
      }
    }
  }



  /// 扫码
  startScan() async {
    if (!await checkCameraPermission()) {
      return;
    }
    await flutterScankit.startScan(scanTypes: [ScanTypes.ALL]);
  }

  @override
  void onClose() {
    flutterScankit.dispose();
    super.onClose();
  }

}